#include "Time2.h"

#include <math.h>


CTime2::CTime2()
	{
	Sec = 0.0;
	Valid = false;
	}


CTime2::~CTime2()
	{
	}


void CTime2::Format(CString &str, int Prec, bool LeadingZero) const
	{
	CString SecStr;
	double s;
	int h, m;

	if (!Valid)
		str = "#ERR";
	else
		{
		s = fabs(Sec);
		h = long(s) / 3600;
		s -= h * 3600.0;
		m = long(s) / 60;
		s -= m * 60.0;
		if (Prec > 0) 
			SecStr.Format("%02.*f", Prec, s);
		else
			SecStr.Format("%02d", int(s + 0.5));
		if (SecStr[0] == '6')
			{
			SecStr.SetAt(0, '0');
			if (++m >= 60)
				{
				h++;
				m -= 60;
				}
			}
		if (LeadingZero || h > 0)
			str.Format("%d:%02d:", h, m);
		else if (m > 0)
			str.Format("%d:", m);
		else
			str = "";
		
		str += SecStr;

		if (Sec < 0.0)
			str = CString(" ") + str;
		}
	}


double CTime2::operator = (CString str)
	{
	int ScanRes;
	int h, m;
	double s;
	bool neg;
	char Dummy;

	Valid = false;
	Sec = 0.0;

	neg = (!str.IsEmpty() && str[0] == '-');
	if (neg)
		str = str.Mid(2);

	for (int Tries = 1 ; Tries <= 3 ; Tries++)
		{
		ScanRes = sscanf(str, "%d:%d:%lf%c", &h, &m, &s, &Dummy);
		if (ScanRes == 3) 
			break;
		str = CString("0:") + str;
		}

	if (ScanRes != 3 || h < 0 || m < 0 || s < 0.0)
		return 0.0;

	Sec = s + 60.0 * m + 3600.0 * h;
	if (neg)
		Sec = -Sec;

	Valid = true;
	return Sec;
	}


